/**
 * 
 */
package com.demo2do.boyle.backend.service.system.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.boyle.backend.service.system.MenuService;
import com.demo2do.boyle.common.entity.system.Menu;
import com.demo2do.boyle.common.entity.system.Role;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.GenericJdbcSupport;
import com.demo2do.core.service.impl.GenericServiceImpl;

/**
 * @author Jason.Y
 *
 */
@Service("menuService")
public class MenuServiceImpl extends GenericServiceImpl<Menu> implements MenuService {

	@Autowired 
	private GenericDaoSupport genericDaoSupport;
	
	@Autowired 
	private GenericJdbcSupport genericJdbcSupport;
	/*
     * (non-Javadoc)
     * @see com.demo2do.boyle.backend.service.MenuService#list()
     */
	@SuppressWarnings("unchecked")
	public List<Role> list() {
		
		List<Role> roles = genericDaoSupport.searchForList("FROM Role");
		return roles;
	}

	@Override
	public String showSelMenu() {
		
		StringBuffer sb = new StringBuffer();
		/*List<Menu> menus = genericDaoSupport.searchForList("FROM Menu where parentId = 0 order by sort desc ");
		
		
		List<Menu> subMenus = genericDaoSupport.searchForList("FROM Menu where parentId <> 0 order by sort desc ");
		*/
		
		return null;
	}

	@Override
	public String loadSelectedMenu() {
		String sentence = " SELECT id,name,parent_id as parentId,flag from menu order by sort ";
        List<Map<String,Object>> menuList = genericJdbcSupport.queryForList(sentence);
		
		StringBuffer sb = new StringBuffer();
        sb.append("[");
		
       for (Map<String, Object> map : menuList) {
			if("0".equals(map.get("parentId"))){
				sb.append("{\"id\":").append("\"" + map.get("id") + "\",");
				sb.append("\"text\":").append("\"" + map.get("name") + "\",");
				sb.append("\"level\":").append("\"" + (!"0".equals(map.get("parentId").toString())?1:0) + "\",");
				sb.append("\"children\":[");
			}
		
			if("1".equals(map.get("flag").toString())){
				sb.append("{\"id\":").append("\"" + map.get("id") + "\",");
				sb.append("\"text\":").append("\"" + map.get("name") + "\",");
				sb.append("\"level\":").append("\"" + (!"0".equals(map.get("parentId").toString())?1:0) + "\"");
				sb.append("}");
			}else if("2".equals(map.get("flag").toString()) || "3".equals(map.get("flag").toString())){
				sb.append(",{\"id\":").append("\"" + map.get("id") + "\",");
				sb.append("\"text\":").append("\"" + map.get("name") + "\",");
				sb.append("\"level\":").append("\"" + (!"0".equals(map.get("parentId").toString())?1:0) + "\"");
				sb.append("}");
			}
			
			if("3".equals(map.get("flag").toString())){
				sb.append("]},");
			}
		}
        
        String s2 = "";
        String s1 = sb.toString().substring(0, sb.toString().lastIndexOf(","));
        s2 = s1 + "]";
        
        return s2;
	}
}
